/*
 * Copyright ©2015-2021 Jaemon. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.jaemon.spring.adorner.core;

import io.gitee.jaemon.spring.adorner.AdornerConstants;
import io.gitee.jaemon.spring.adorner.util.FileUtils;
import io.gitee.jaemon.spring.adorner.util.LoggerHelper;
import io.gitee.jaemon.spring.adorner.util.StringUtils;

import java.io.File;
import java.io.PrintStream;
import java.time.LocalDateTime;

/**
 * 日志配置
 *
 * @author Jaemon
 * @since 1.0
 */
public class AdornerLogConfig extends LoggerHelper {

    /**
     * 加载日志配置
     *
     * @param context
     *      Adorner上下文信息
     */
    static void loadLogConfig(AdornerApplicationContext context) {
        try {
            sysLlogLevel = context.logLevel();
            if (context.isLogger()) {
                load(context);
            } else {
                logger(context.banner().printBanner());
            }
        } catch (Exception ex) {
            error("配置异常, message=%s.", ex.getMessage());
            System.exit(1);
        }
    }

    private static void load(AdornerApplicationContext context) throws Exception {
        String logFile = context.logpath();
        if (StringUtils.isNotEmpty(logFile)) {
            String pathname = logFile + AdornerConstants.DEFAULT_LOG_FILE;
            File loggerFile = new File(pathname);
            String fileName = loggerFile.getName();
            String oldFilePath = null;
            // 处理备份
            if (loggerFile.exists()) {
                String now = LocalDateTime.now().format(AdornerConstants.DATETIME_FORMAT);
                String[] nowTime = now.split(" ");
                String oldFileName = fileName.replaceAll("\\.", "_" + nowTime[1] + ".");
                oldFilePath = loggerFile.getParent() + File.separator + nowTime[0] + File.separator + oldFileName;
                FileUtils.copyFile(loggerFile, new File(oldFilePath));
            }
            PrintStream logger = new PrintStream(loggerFile);
            System.setOut(logger);
            System.setErr(logger);
            isLogger = true;

            logger(context.banner().printBanner());
            if (StringUtils.isNotEmpty(oldFilePath)) {
                warn("file=%s already exists and back up on %s.", fileName, oldFilePath);
            }
        }
    }
}